from django_redis import get_redis_connection

import base64, pickle


"""登录时合并购物车"""
"""QQ登录和账号登录时都要进行购物车合并"""
def merge_cart_cookie_to_redis(request, response):

    # 获取cookie购物车数据
    cart_str = request.COOKIES.get('carts')
    user = request.user

    if cart_str is None:
        return

    cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))

    """
        {
            1: {'count': 1, 'selected': True}
        }
    """

    # 创建redis连接对象
    redis_conn = get_redis_connection('carts')
    pl = redis_conn.pipeline()

    #遍历cookie大字典
    for sku_id, sku_dict in cart_dict.items():
        # {sku_id, sku_dict}
        pl.hset('carts_%s' % user.id, sku_id, sku_dict['count'])  # 将cookie中的sku_id count 向redis的hash去存

        if sku_dict['selected']:
            pl.sadd('selected_%s' % user.id, sku_id)  # 如果当前cookie中的商品是勾选就把勾选商品sku_id向set集合添加
        else:
            pl.srem('selected_%s' % user.id, sku_id)  # 如果没有勾选就从redis中移除

    pl.execute()

    response.delete_cookie('carts')  # 清空cookie购物车数据

